//
//  JXWAppDelegate.m
//  JXWShoppingIPad
//
//  Created by zheng ji on 14-1-15.
//  Copyright (c) 2014年 jxw. All rights reserved.
//
#import "JXWAppDelegate.h"
#import "Constants.h"
#import "CommonConfigUtil.h"
#import "MobClick.h"
//#import "CJSONDeserializer.h"

@implementation JXWAppDelegate

 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if(!IsIOS7){
        
      // [[UINavigationBar appearance] setTintColor:[UIColor colorWithRed:244/255.0f green:164/2552 blue:92                      /255.0f alpha:0.5]];
     //              [[UITabBar appearance] setTintColor:[UIColor colorWithRed:244/255.0f green:164/2552 blue:92                      /255.0f alpha:0.5]];
    }else{
        
      //   [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:244/255.0f green:164/2552 blue:92                      /255.0f alpha:0.5]];
        
       
    }
    if(!IsIOS7){
        
    [[UITabBarItem appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:
      [UIColor whiteColor], UITextAttributeTextColor,
      [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0], UITextAttributeTextShadowColor,
      [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,
      [UIFont fontWithName:@"AmericanTypewriter" size:18], UITextAttributeFont,
      nil]  forState:UIControlStateNormal];
    
    [[UITabBarItem appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:
      [UIColor whiteColor], UITextAttributeTextColor,
      [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0], UITextAttributeTextShadowColor,
      [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,
      [UIFont fontWithName:@"AmericanTypewriter" size:23], UITextAttributeFont,
      nil]  forState:UIControlStateSelected];
    }
    [self initApp];
  
    
    //向微信注册
    
    [WXApi registerApp:@"wx4906e1d3e9afa9d3" withDescription:@"家乡味"];
  
    
    return YES;
}
//微信方法
-(void)onReq:(BaseReq *)req{
    
}
//微信方法
-(void)onResp:(BaseResp *)resp{
    
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
    NSLog(@"url %@ isSuc %d",url,isSuc == YES ? 1 : 0);
    return  isSuc;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if(nil==advList){
        advList=[[NSMutableArray alloc] init];
    }
       [NSThread detachNewThreadSelector:@selector(createAdvListThread) toTarget:self withObject:nil];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void)clearCacheImage{
    
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSString *path=[CommonConfigUtil getImageLocalPath];
    [fileManager removeItemAtPath:path error:nil];
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    
    
    
    NSString *filestorePath=[CommonConfigUtil getFileLocalPath];
    if(![fileManager fileExistsAtPath:filestorePath ]){
        [fileManager createDirectoryAtPath:filestorePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
 
}

- (void)addMobileUser:(NSString *)isSleep{
    
      
    if(nil!=isSleep && [@"Y" isEqualToString:isSleep]){
        [NSThread sleepForTimeInterval:5];
    }
    
    if(![CommonConfigUtil checkNetworkReachable]){
		return ;
	}
    
    NSString *openUDID=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
    /*
    NSString *openUDID=[OpenUDID value];
    if(nil==openUDID||[@"" isEqualToString:openUDID]){
        return;
    }*/
    
    NSString *deviceInfo= [CommonConfigUtil getDeviceInfo];
    
    NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@/saveMobileuser/?type=%@&uuid=%@&appversion=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getVersionType],openUDID,[CommonConfigUtil getMobileClientApp]];
    
    
    if(nil!=[myDefaults objectForKey:@"userId"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userId"]]){
        [url appendFormat:@"&userid=%@", [myDefaults objectForKey:@"userId"]];
    }
    
    if(nil!=[myDefaults objectForKey:@"userNickname"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userNickname"]]){
        [url appendFormat:@"&username=%@", [[myDefaults objectForKey:@"userNickname"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[myDefaults objectForKey:@"deviceToken"]&&![@"" isEqualToString:[myDefaults objectForKey:@"deviceToken"]]){
        [url appendFormat:@"&token=%@",[[myDefaults objectForKey:@"deviceToken"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=deviceInfo&&![@"" isEqualToString:deviceInfo]){
        [url appendString:deviceInfo];
    }
    
    // NSLog(@"url:%@",url);
    
    //  NSData *reData=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    // [url release];
    
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:
                           NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    
    NSHTTPURLResponse *urlResponse;
    NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    
    
    
    
    if(nil!=reData && [reData length]>0){
        NSError *error=nil;
  
        
        NSDictionary *dictionary= [NSJSONSerialization JSONObjectWithData:reData options:kNilOptions error:&error];
        if(!error){
            NSString  *taobosid=[dictionary objectForKey:@"sid"];//toabosid
            if(nil!=taobosid && ![@"" isEqualToString:taobosid]){
                [myDefaults setObject:taobosid forKey:@"taobosid"];
                [myDefaults synchronize];
            }
            
        }
    }
    
    
    reData=nil;
    
    
    
    
    
    
}

-(void)initApp{
    
     [MobClick startWithAppkey:[CommonConfigUtil getUmengAppKey] reportPolicy:REALTIME channelId:[CommonConfigUtil getChannelId]];
    // [self createAdvList];
    
    //应用启动时先清理掉本地暂存的图片
    
    [NSThread detachNewThreadSelector:@selector(clearCacheImage) toTarget:self withObject:nil];
    
    
    
    myDefaults=[NSUserDefaults standardUserDefaults];
    if(nil==[myDefaults objectForKey:@"audioPlay"] || [@"" isEqualToString:[myDefaults objectForKey:@"audioPlay"]]){
        [myDefaults setObject:@"N" forKey:@"audioPlay"];
        [myDefaults synchronize];
    }
    
   // [NSThread detachNewThreadSelector:@selector(getCoverInfo) toTarget:self withObject:nil];
    
    [NSThread detachNewThreadSelector:@selector(addMobileUser:) toTarget:self withObject:@"N"];
    
    UIInterfaceOrientation t_orientation=[[UIApplication sharedApplication] statusBarOrientation ];
    
    if(t_orientation==UIInterfaceOrientationLandscapeLeft||t_orientation==UIInterfaceOrientationLandscapeRight){
        landScape=YES;
    }else{
        
        landScape=NO;
        
    }
   
}
-(NSMutableArray *)getAdvList{
    if(advList==nil){
        [self createAdvList];
    }
    return advList;
}
-(void)createAdvList{
    if(nil==advList){
        advList=[[NSMutableArray alloc] init];
    }
    
   // [NSThread detachNewThreadSelector:@selector(createAdvListThread) toTarget:self withObject:nil];
    [self createAdvListThread];
    
}

-(void)createAdvListThread{
    
    
      
    if([CommonConfigUtil checkNetworkReachable]){
		
        NSString *url = [[NSString alloc] initWithFormat:@"%@/ad/list/?category=%@&coverId=%@&appID=%@&app=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getAppAdvType],[CommonConfigUtil getCoverId],[CommonConfigUtil getApp]
                         ,[CommonConfigUtil getApp]];
        
        //  NSLog(@"url:%@",url);
        
        NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:
                               NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
        
        NSHTTPURLResponse *urlResponse;
        NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
        
      
        
        // NSLog(@"reData:%@",reData);
		
        NSError *error=nil;
      //  NSDictionary *dictionary=[[CJSONDeserializer deserializer] deserializeAsDictionary:reData error:&error];
           NSDictionary *dictionary= [NSJSONSerialization JSONObjectWithData:reData options:kNilOptions error:&error];
        
        if(!error){
            
            [advList removeAllObjects];
            
            NSArray *advArray=[dictionary objectForKey:@"adList"];
            for(int i=0;nil!=advArray&&i<[advArray count];i++){
                NSMutableDictionary *currentAdv=[[NSMutableDictionary alloc] initWithCapacity:0];
                //类型 0：商品详细页 1：分类列表 2：标签列表 3：店铺详细 4：品牌详细 5：专辑详细 6：场景详细 7：活动详细 8：appstore 9:url
                
                
                NSString *advid=[[advArray objectAtIndex:i] objectForKey:@"id"];//广告id
                NSString *advtype=[[advArray objectAtIndex:i] objectForKey:@"type"];
                NSString *name=[[advArray objectAtIndex:i] objectForKey:@"name"];//广告名称
                NSString *photo=[[advArray objectAtIndex:i] objectForKey:@"photo"];//图路径
                NSString *fullPath=[[advArray objectAtIndex:i] objectForKey:@"fullPath"];//图路径
                NSString *objectid=[[advArray objectAtIndex:i] objectForKey:@"objectid"];//内容ID
                NSString *objectName=[[advArray objectAtIndex:i] objectForKey:@"objectName"];//内容名称
                NSString *urlparams=[[advArray objectAtIndex:i] objectForKey:@"urlparams"]; //url附加参数
                NSString *loaclPhotoPath;
                
                if(nil==advtype)advtype=@"";
                if(nil==name)name=@"";
                if(nil==fullPath)fullPath=@"";
                if(nil==objectid)objectid=@"";
                if(nil==objectName)objectName=@"";
                if(nil==advid)advid=@"";
                if(nil==urlparams)urlparams=@"";
                
                if(nil==photo){
                    loaclPhotoPath=[NSString stringWithFormat:@"%@/adv_image_%@.jpg",[CommonConfigUtil getImageLocalPath],advid];
                }
                else{
                    NSString *fileName=[photo stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
                    
                    loaclPhotoPath=[NSString stringWithFormat:@"%@/adv_%@",[CommonConfigUtil getImageLocalPath],fileName];//age图
                    
                    //loaclPhotoPath=[NSString stringWithFormat:@"%@/%@",[CommonConfigUtil getFileLocalPath],photo];
                }
                
                [currentAdv setObject:advid forKey:@"advid"];//广告id
                [currentAdv setObject:advtype forKey:@"advtype"];//类型
                [currentAdv setObject:name forKey:@"name"];//类型
                [currentAdv setObject:fullPath forKey:@"image"];
                [currentAdv setObject:objectid forKey:@"objectId"];
                [currentAdv setObject:objectName forKey:@"objectName"];
                [currentAdv setObject:loaclPhotoPath forKey:@"adv_image_local"];
                [currentAdv setObject:urlparams forKey:@"urlparams"];
                
                
                
                [advList addObject:currentAdv];
                
                
                
                
                
            }
            
            
            
        }
        
    }
    
    
    
    
}
//分享到微信朋友圈
-(void)shareToWeiXinTimeLine:(NSString*) shareLink text:(NSString*) text title:(NSString*) title{
    [self shareToWeiXin:shareLink text:text title:title scene:WXSceneTimeline];
}
//分享到微信收藏
-(void)shareToWeiXinFavorite:(NSString*) shareLink text:(NSString*) text title:(NSString*) title{
    [self shareToWeiXin:shareLink text:text title:title  scene:WXSceneFavorite];
}
//分享微信朋友
-(void)shareToWeiXinFriend:(NSString*) shareLink text:(NSString*) text title:(NSString*) title{
    [self shareToWeiXin:shareLink text:text title:title  scene:WXSceneSession];
}
//分享到微信
-(void)shareToWeiXin:(NSString*) shareLink text:(NSString*) text title:(NSString*) title scene:(NSInteger)scene{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;
    message.description = text;
    
    [message setThumbImage:[UIImage imageNamed:@"Icon@2x.png"]];
    
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = shareLink;
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = scene;
    
    [WXApi sendReq:req];
}
 
@end
